package operation

import (
	"../common"
	"../web"
	"strings"
)

type OperSelectObj struct {
	common.BaseHandler
}

func (self *OperSelectObj) Prepare() {
	computer := strings.TrimSpace(strings.Split(self.Ctx.Request.RemoteAddr, ":")[0])
	spRtnData := *common.FetchOneRowPtr(
		`SELECT TOP 1 STATION, LINE 
           FROM SFC_COMPUTER(NOLOCK) 
          WHERE COMPUTER = ?`,
		self.Usr.Conn, new(common.Computer), computer)
	station := spRtnData.(common.Computer).Station
	line := spRtnData.(common.Computer).Line

	wonos := *common.FetchAllRowsPtr(
		`SELECT A.WONO, A.WOTYPE, A.ITEM, ISNULL(B.DESCRIP,''), A.QTY 
           FROM SFC_WO A(NOLOCK), SFC_ITEMS B(NOLOCK) 
          WHERE A.LOCKED = 0 
            AND A.CLOSED = 0 
            AND A.ITEM=B.ITEM 
          ORDER BY A.WONO`,
		self.Usr.Conn, new(common.WorkOrder))

	self.TmplData["station"] = station
	self.TmplData["line"] = line
	self.TmplData["wonos"] = wonos
}

func (self *OperSelectObj) ParameterCheck() bool {
	self.Html = "normalflow.html"

	station := self.TmplData["station"].(string)
	if station == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please set the computer first.")
		return false
	}

	c_wono := self.Ctx.Params["wono"]
	if c_wono == "" {
		self.TmplData["error"] = common.GetText(self.Lang, "Please select the WorkOrder.")
		return false
	}

	iHasSta := *common.FetchOneRowPtr(
		`SELECT COUNT(CURR_STATION) 
		   FROM SFC_ROUTING(NOLOCK) 
		  WHERE NAME=(
				  SELECT TOP 1 ISNULL(ROUTING, '') 
				    FROM SFC_WO(NOLOCK) 
				   WHERE WONO=?) 
	        AND CURR_STATION=?`,
		self.Usr.Conn, new(common.RecCount), c_wono, station)
	hasStation := iHasSta.(common.RecCount).Number
	if hasStation == 0 {
		iHasSta = *common.FetchOneRowPtr(
			`SELECT COUNT(CURR_STATION) 
			   FROM SFC_ROUTING(NOLOCK) 
			  WHERE NAME IN (
					SELECT REPAIR_STATION FROM SFC_ROUTING(NOLOCK) WHERE NAME=(
					  	SELECT TOP 1 ISNULL(ROUTING, '') 
					      FROM SFC_WO(NOLOCK) 
					   	 WHERE WONO=?))
		        AND CURR_STATION=?`,
			self.Usr.Conn, new(common.RecCount), c_wono, station)
		hasStation = iHasSta.(common.RecCount).Number
		if hasStation == 0 {
			self.TmplData["error"] = common.GetText(self.Lang,
				"WorkOrder process does not include this station.")
			return false
		} else {
			iMustTest := *common.FetchOneRowPtr(
				`SELECT MUSTBETEST
				   FROM SFC_ROUTING(NOLOCK) 
				  WHERE NAME IN (
							SELECT REPAIR_STATION FROM SFC_ROUTING(NOLOCK) WHERE NAME=(
							  	SELECT TOP 1 ISNULL(ROUTING, '') 
							      FROM SFC_WO(NOLOCK)
						   WHERE WONO=?))
			        AND CURR_STATION=?`,
				self.Usr.Conn, new(common.RecCount), c_wono, station)
			mustTest := iMustTest.(common.RecCount).Number
			if mustTest == 1 {
				self.TmplData["error"] = common.GetText(self.Lang,
					"The products must be tested at the site [%s], it can't be manually scanned.",
					station)
				return false
			}
		}
	} else {
		iMustTest := *common.FetchOneRowPtr(
			`SELECT MUSTBETEST 
			   FROM SFC_ROUTING(NOLOCK) 
			  WHERE NAME=(
					  SELECT TOP 1 ISNULL(ROUTING, '') 
					    FROM SFC_WO(NOLOCK) 
					   WHERE WONO=?) 
		        AND CURR_STATION=?`,
			self.Usr.Conn, new(common.RecCount), c_wono, station)
		mustTest := iMustTest.(common.RecCount).Number
		if mustTest == 1 {
			self.TmplData["error"] = common.GetText(self.Lang,
				"The products must be tested at the site [%s], it can't be manually scanned.",
				station)
			return false
		}
	}

	var c_item string
	wonos := self.TmplData["wonos"].([]interface{})
	for _, value := range wonos {
		if c_wono == value.(common.WorkOrder).Wono {
			c_item = value.(common.WorkOrder).Item

			self.TmplData["wono"] = c_wono
			self.TmplData["item"] = c_item
			self.TmplData["wo_type"] = value.(common.WorkOrder).Wotype
			self.TmplData["desc"] = value.(common.WorkOrder).Desc
			self.TmplData["wo_qty"] = value.(common.WorkOrder).Qty
			break
		}
	}

	delete(self.TmplData, "wonos") // not use when goto the detail operation

	parts := *common.FetchAllRowsPtr(
		`SELECT ROW_NUMBER() OVER(ORDER BY IDX), PARTNAME, ISNULL(DESCRIP, '')
           FROM SFC_PARTSETTING(NOLOCK) 
          WHERE ITEM=? 
            AND STATION=?`,
		self.Usr.Conn, new(common.PartName), c_item, station)

	leng := len(parts)
	iRtnData := *common.FetchOneRowPtr(
		`SELECT TOP 1 ISNULL(PASSED, 0) 
           FROM SFC_PASSED(NOLOCK) 
          WHERE WONO=? 
            AND STATION=?`,
		self.Usr.Conn, new(common.RecDataStr), c_wono, station)
	passedqty := iRtnData.(common.RecDataStr).Data

	self.TmplData["passedqty"] = passedqty

	if self.Lang == "zh_CN" {
		failcodes := *common.FetchAllRowsPtr(
			`SELECT FAILCODE, DESCCHN 
           	   FROM SFC_FAILURE(NOLOCK) 
          	  ORDER BY FAILCODE`,
			self.Usr.Conn, new(common.Failure))
		self.TmplData["failcodes"] = failcodes
	} else {
		failcodes := *common.FetchAllRowsPtr(
			`SELECT FAILCODE, FAILDESC 
           	   FROM SFC_FAILURE(NOLOCK) 
          	  ORDER BY FAILCODE`,
			self.Usr.Conn, new(common.Failure))
		self.TmplData["failcodes"] = failcodes
	}

	if leng > 0 {
		parts_m := parts[:leng-1]
		parts_f := parts[leng-1:][0]
		self.TmplData["parts_m"] = parts_m
		self.TmplData["parts_f"] = parts_f
		self.Html = "scanpartsdetails.html"
		return false
	}

	if station == "WO PACKING" {
		self.Html = "packflow.html"
		return false
	}

	pimData := *common.FetchOneRowPtr(
		`SELECT PRODTYPE, FREQUENCY, SPECIFICATION, HTMLFILE 
		   FROM SFC_PIMSETTING(NOLOCK) 
		  WHERE ITEM=? AND STATION=?`,
		self.Usr.Conn, new(common.PassivePim), c_item, station)
	ptype := strings.TrimSpace(pimData.(common.PassivePim).PrdType)
	freqy := strings.TrimSpace(pimData.(common.PassivePim).Band)
	limit := strings.TrimSpace(pimData.(common.PassivePim).Limit)
	htmlf := strings.TrimSpace(pimData.(common.PassivePim).Htmlfile)
	if ptype == "A" && station == "WO TESTING-PIM-FINAL" {
		var lmt_idx []int
		if limit != "" {
			lmt_ls := strings.Split(limit, ",")
			for i, _ := range lmt_ls {
				lmt_idx = append(lmt_idx, i+1)
			}
		}
		if freqy != "" {
			s_band := strings.Split(freqy, ",")
			self.TmplData["band"] = s_band
			self.TmplData["limitval"] = limit
			self.TmplData["freqy"] = freqy
			self.TmplData["limitlist"] = lmt_idx
			self.Html = htmlf
		} else if htmlf == "2323PIM.html" {
			self.Html = htmlf
			self.TmplData["limitlist"] = lmt_idx
		} else {
			self.Html = "scanflow.html"
		}
		return false
	}
	if ptype == "B" && freqy != "" {
		s_band := strings.Split(freqy, ",")
		self.TmplData["band"] = s_band
		self.TmplData["limitval"] = limit
		self.TmplData["freqy"] = freqy
		self.Html = htmlf
		return false
	}

	if station == "WO LINK CUSTOMER" {
		if self.TmplData["ProductionLine"] == "SFPRD02" {
			self.TmplData["error"] = common.GetText(self.Lang, "Please get the program that can link the customer ID and print label.")
			return false
		}
	}

	self.Html = "scanflow.html"

	return false
}

func (self *OperSelectObj) SqlExecute() bool {
	return false
}

func ScanFlowHandler(ctx *web.Context) {
	self := new(OperSelectObj)
	self.Ctx = ctx
	self.Html = "normalflow.html"
	self.Rightlist = []string{"scanflow"}
	self.Do(self)
}
